package com.whmskj.xjlhsc.mobie.index.service.impl;

import com.whmskj.xjlhsc.mapper.Sb02EquipmentCounterAccountMapper;
import com.whmskj.xjlhsc.mapper.ShachangsbbanyieldMapper;
import com.whmskj.xjlhsc.mobie.index.entity.dto.XsTrendDto;
import com.whmskj.xjlhsc.mobie.index.entity.vo.XsTrendVo;
import com.whmskj.xjlhsc.mobie.index.service.IndexService;
import com.whmskj.xjlhsc.view.entity.vo.StateVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.format.DateTimeFormatters;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 张
 * @version 1.0
 */

@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private ShachangsbbanyieldMapper shachangsbbanyieldMapper;
    @Autowired
    private Sb02EquipmentCounterAccountMapper sb02EquipmentCounterAccountMapper;

    @Override
    public Map<String, Object> xsEnergy() {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> yesterdayData = shachangsbbanyieldMapper.selectXsEnergy();
        resultMap.put("yesterdayAvgEnergy", yesterdayData.get("avgEnergy"));
        resultMap.put("yesterdayAvgTEnergy", yesterdayData.get("avgTEnergy"));

        LocalDate now = LocalDate.now();
        String startTime = "";
        String endTime = "";
        int dayOfMonth = now.getDayOfMonth();

        if (dayOfMonth >= 20) {
            startTime = now.getYear() + "-" + now.getMonthValue() + "-" + 20;
        } else {
            startTime = now.getYear() + "-" + (now.getMonthValue() - 1) + "-" + 20;
        }
        endTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Map<String, Object> monthData = shachangsbbanyieldMapper.selectMonthXsEnergy(startTime, endTime);
        resultMap.put("monthAvgEnergy", monthData.get("monthAvgEnergy"));
        resultMap.put("monthAvgTEnergy", monthData.get("monthAvgTEnergy"));
        return resultMap;
    }

    /**
     * 细纱能耗趋势
     *
     * @return
     */
    @Override
    public List<XsTrendVo> xsTrend() {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 计算本周日期范围（周一到周日）
        LocalDate thisWeekMonday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate thisWeekSunday = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));


        List<XsTrendDto> curWeekXsTrendDtoList = shachangsbbanyieldMapper.selectXsTrend(thisWeekMonday, thisWeekSunday);
        Map<String, List<XsTrendDto>> collect = curWeekXsTrendDtoList.stream().collect(Collectors.groupingBy(XsTrendDto::getDay));



        // 计算上周日期范围（周一到周日）
        LocalDate lastWeekMonday = thisWeekMonday.minusWeeks(1);
        LocalDate lastWeekSunday = thisWeekSunday.minusWeeks(1);
        List<XsTrendDto> lastWeekXsTrendDtoList = shachangsbbanyieldMapper.selectXsTrend(lastWeekMonday, lastWeekSunday);

        Map<String, List<XsTrendDto>> collect1 = lastWeekXsTrendDtoList.stream().collect(Collectors.groupingBy(XsTrendDto::getDay));

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<XsTrendVo> xsTrendVoList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            XsTrendVo xsTrendVo = new XsTrendVo();
            String day = thisWeekMonday.plusDays(i).format(dateTimeFormatter);
            double curEnergy = collect.get(day) == null ? 0 : collect.get(day).get(0).getEnergy();
            String day2 = lastWeekMonday.plusDays(i).format(dateTimeFormatter);
            double lastEnergy = collect1.get(day2) == null ? 0 : collect1.get(day2).get(0).getEnergy();

            xsTrendVo.setWeek(getWeekDay(day));
            xsTrendVo.setCurEnergy(curEnergy);
            xsTrendVo.setLastEnergy(lastEnergy);
            xsTrendVoList.add(xsTrendVo);
        }


        return xsTrendVoList;
    }

    @Override
    public List<StateVo> getState() {
       return sb02EquipmentCounterAccountMapper.selectIndexState();
    }

    public String getWeekDay(String dateStr) {
        try {
            // 解析输入的日期字符串
            LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);

            // 获取星期几（枚举值）
            DayOfWeek dayOfWeek = date.getDayOfWeek();

            // 转换为中文星期（也可直接用 dayOfWeek.toString() 获取英文）
            String chineseDay = switch (dayOfWeek) {
                case MONDAY -> "周一";
                case TUESDAY -> "周二";
                case WEDNESDAY -> "周三";
                case THURSDAY -> "周四";
                case FRIDAY -> "周五";
                case SATURDAY -> "周六";
                case SUNDAY -> "周日";
            };
            return chineseDay;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        int dayOfMonth = now.getDayOfMonth();

        if (dayOfMonth >= 20) {
            System.out.println(now.getYear() + "-" + now.getMonthValue() + "-" + 20);
        } else {
            System.out.println(now.getYear() + "-" + (now.getMonthValue() - 1) + "-" + 20);
        }
        System.out.println(dayOfMonth);
    }
}
